<template>
  <div class="login-container">
    <div class="login-card">
      <!-- 标题部分 -->
      <div class="header">
        <img src="@/assets/vue.svg" class="logo" alt="logo">
        <p class="subtitle">欢迎使用后台管理系统</p>
      </div>

      <!-- 登录表单 -->
      <el-form :model="loginForm" class="form-wrapper">
        <!-- 邮箱输入 -->
        <el-form-item>
          <el-input v-model="loginForm.email" placeholder="请输入QQ邮箱" class="custom-input">
            <template #append>
              <span class="email-suffix">@qq.com</span>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item>
          <el-input v-model="loginForm.password" placeholder="请输入密码" class="custom-input">
          </el-input>
        </el-form-item>

        <!-- 验证码输入 -->
        <el-form-item>
          <div class="code-group">
            <el-input v-model="loginForm.code" placeholder="请输入验证码" class="code-input" />
            <el-button type="primary" :disabled="codeTimer > 0" class="code-btn" @click="getCode">
              {{ codeText }}
            </el-button>
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-button type="primary" class="login-btn" @click="handleLogin">
          立即登录
        </el-button>
        <div class="forgot-password" @click="handleForgotPassword">
          忘记密码？
        </div>
      </el-form>

    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import md5 from 'js-md5';
import { ElMessage, ElNotification } from 'element-plus'
import { useRouter } from 'vue-router';


const loginForm = ref({ email: '', code: '', password: '' })
const codeTimer = ref(0)
const verificationCode = ref(0)
const router = useRouter();

let timer = null

const codeText = computed(() =>
  codeTimer.value > 0 ? `${codeTimer.value}秒后重试` : '获取验证码'
)

const getCode = () => {
  if (!loginForm.value.email) {
    ElMessage.error('请输入邮箱地址')
    return
  }
  codeTimer.value = 60

  let url = 'http://localhost:8181/user/sendEmailVerificationCode?email=';
  url += loginForm.value.email + '@qq.com';
  fetch(url, {
    method: 'POST',
    header: {
      'Content-Type': 'text/plain',
      'Accept': 'application/json',
    }
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }
    return response.json();
  }).then(data => {
    if (data['code'] == 200) {
      verificationCode.value = data['data'].match(/\d+/)[0];
      console.log(verificationCode.value);
      timer = setInterval(() => {
        codeTimer.value > 0 ? codeTimer.value-- : clearInterval(timer)
      }, 1000)
    }
    else {
      ElNotification({
        title: 'Error',
        message: data['msg'],
        type: 'error',
      })
    }
  }).catch(error => console.error('Error:', error));
}

const handleLogin = () => {
  if (!loginForm.value.email || !loginForm.value.password || !loginForm.value.code) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (loginForm.value.code != verificationCode.value) {
    ElNotification({
      title: 'Error',
      message: '验证码错误',
      type: 'error',
    })
    return
  }
  fetch('http://localhost:8181/user/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
    body: JSON.stringify({
      email: loginForm.value.email + '@qq.com',
      password: md5(loginForm.value.password)
    })
  }).then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`)
    }
    return response.json();
  }).then(data => {
    if (data['code'] != 200) {
      ElNotification({
        title: 'Error',
        message: data['msg'],
        type: 'error',
      })
    } else {
      localStorage.setItem('tokenName', data['data']['tokenName']);
      localStorage.setItem('tokenValue', data['data']['tokenValue']);
      console.log(localStorage.getItem('tokenName') + '\n' + localStorage.getItem('tokenValue'))
      ElMessage({
        message: '登录成功',
        type: 'success'
      })
      if(router) {
        router.push('/home');
      } else {
        console.error("Router is undefined");
      }
    }
  }).catch(error => console.error('Error: ', error));
}

// 新增忘记密码处理方法
const handleForgotPassword = () => {
  ElMessage.warning('请联系管理员重置密码')
}
</script>

<style scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;

  /* 背景设置 */
  background: linear-gradient(rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.3)),
    url('@/assets/zhuye.jpeg');
  background-size: cover;
  background-position: center;
}

.login-card {

  width: 350px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);

  position: relative;
  z-index: 1;
}

.title {
  color: #fff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.subtitle {
  color: rgba(255, 255, 255, 0.8);
}

/* 调整输入框背景 */
:deep(.el-input__inner) {
  background: rgba(255, 255, 255, 0.9);
}


/* 头部样式 */
.header {
  text-align: center;
  margin-bottom: 36px;
}

.logo {
  width: 60px;
  margin-bottom: 16px;
}

.title {
  color: #303133;
  font-size: 24px;
  margin-bottom: 8px;
}

.subtitle {
  color: #909399;
  font-size: 14px;
}

/* 表单样式 */
.form-wrapper {
  margin: 30px 0;
}

/* 输入框样式 */
:deep(.custom-input .el-input-group) {
  display: flex;
}

:deep(.custom-input .el-input__wrapper) {
  flex: 1;
  width: 100%;
}

/* 验证码组容器 */
.code-group {
  display: flex;
  width: 100%;
  /* 新增 */
  gap: 10px;
}

/* 验证码输入框 */
.code-input {
  flex: 2;
  /* 调整比例 */
}

:deep(.el-input__inner),
.code-btn {
  height: 48px !important;
}

/* 统一圆角 */
:deep(.el-input__inner),
.code-btn {
  border-radius: 8px;
}

/* 登录按钮 */
.login-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(135deg, #ff4444, #ff6b6b);
}

.forgot-password {
  margin-top: 16px;
  text-align: center;
  color: #409eff;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
}

.forgot-password:hover {
  color: #337ecc;
  text-decoration: underline;
}

/* 调整登录按钮间距 */
.login-btn {
  margin-bottom: 8px;
}
</style>